//
//  PxHomeViewController.m
//  OilCard
//
//  Created by Xu Yefeng on 14-5-18.
//  Copyright (c) 2014年 Free. All rights reserved.
//

#import "PxWayBillNotifyViewController.h"
#import "PxFormValidate.h"

@implementation PxWayBillNotifyViewController {
    BOOL isContinues;
    NSArray *compArray;
    NSString *companyCode;
    NSString *expressCompany;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        isContinues = NO;
        compArray = [PxGlobal getData:COMPANY_INFO];
        if (compArray.count > 0) {
            companyCode = compArray[0][@"value"];
            expressCompany = compArray[0][@"label"];
        } else {
            companyCode = @"error";
            expressCompany = @"error";
        }
    }
    return self;
}

-(void)fingerTapped:(UITapGestureRecognizer *)gestureRecognizer
{
    [self.view endEditing:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    UITapGestureRecognizer *viewTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fingerTapped:)];
    
    [self.view addGestureRecognizer:viewTap];
    
    UIView *titleView = [self setLogoTitleViewWithTitle:@"扫描上架"];
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gotoScanPage)];
    
    [titleView addGestureRecognizer:singleTap];
    
    self.contentView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    CGFloat contentheight = CGRectGetHeight(self.view.frame);// - [PxGlobal getBaseHeight:NO];
    self.contentView.height = contentheight;
    [self.view addSubview:self.contentView];
    
    // Do any additional setup after loading the view.
    self.arr1 = [[NSMutableArray alloc] init];
    self.arr2 = [[NSMutableArray alloc] init];
    self.arr3 = [[NSMutableArray alloc] init];
    for (int i=0; i<100; i++) {
        if (i ==0) {
            [self.arr1 addObject:@"室外"];
        } else
            [self.arr1 addObject:[NSString stringWithFormat:@"%i号架", i]];
        [self.arr2 addObject:[NSString stringWithFormat:@"%i排", i]];
        [self.arr3 addObject:[NSString stringWithFormat:@"%i号", i]];
    }
    CGFloat width = self.view.width;
    CGFloat height = [PxGlobal getCustomerHeight:85];
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
    bgView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:bgView];
    
    CGFloat pickerheight = [PxGlobal getCustomerHeight:10];
    CGFloat pickerWidth = [PxGlobal getCustomerWidth:15];
    CGFloat viewHeight = bgView.height - 2*pickerheight;
    
    PxCompositePickerView *pickerView = [[PxCompositePickerView alloc] initWithFrame:CGRectMake(pickerWidth, pickerheight, bgView.width - 2*pickerWidth, viewHeight)];
    [pickerView setData:[NSMutableArray arrayWithObjects:self.arr1, self.arr2, self.arr3, nil]];
    [bgView addSubview:pickerView];
    _pickerView = pickerView;
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, bgView.bottom-1, self.view.width, 1)];
    lineView.backgroundColor = [UIColor colorWithHTMLStr:@"cccccc"];
    [self.contentView addSubview:lineView];
    
    PxTextField *textfield2 = [PxWidgetCreater getTextField:@"代收运费"];
    textfield2.delegate = self;
    textfield2.frame = CGRectMake(0, lineView.bottom, width/2, [PxGlobal getCustomerHeight:45]);
    textfield2.keyboardType = UIKeyboardTypePhonePad;
    [self.contentView addSubview:textfield2];
    self.freightTextField = textfield2;
    
    UIView *line3 = [[UIView alloc] initWithFrame:CGRectMake(textfield2.right-1, textfield2.top, 1, textfield2.height)];
    line3.backgroundColor = [UIColor colorWithHTMLStr:@"cccccc"];
    [self.contentView addSubview:line3];
    
    PxTextField *textfield4 = [PxWidgetCreater getTextField:@"代收货款"];
    textfield4.delegate = self;
    [textfield4 linkPreField:textfield2];
    textfield4.frame = CGRectMake(textfield2.right, lineView.bottom, width/2, [PxGlobal getCustomerHeight:45]);
    textfield4.keyboardType = UIKeyboardTypePhonePad;
    [self.contentView addSubview:textfield4];
    self.paymentTextField = textfield4;
    
    UIView *line2 = [PxGlobal duplicate:lineView];
    line2.top = textfield4.bottom -1;
    [self.contentView addSubview:line2];
    
    PxTextField *textfield = [PxWidgetCreater getTextField:@"手机号"];
    textfield.tag = 10000;
    textfield.clearsOnBeginEditing = NO;
    [textfield linkPreField:textfield4];
    textfield.delegate = self;
    textfield.frame = CGRectMake(0, line2.bottom, width/2, [PxGlobal getCustomerHeight:45]);
    textfield.keyboardType = UIKeyboardTypePhonePad;
    [self.contentView addSubview:textfield];
    self.telTextField = textfield;
    
    UIView *line4 = [PxGlobal duplicate:line3];
    line4.top = textfield4.bottom -1;
    [self.contentView addSubview:line4];
    
    PxTextField *textfield5 = [PxWidgetCreater getTextField:@""];
    textfield5.indent = 5;
    textfield5.tag = 10001;
    textfield5.frame = CGRectMake(textfield.right, line2.bottom, width/2, [PxGlobal getCustomerHeight:45]);
    [self.contentView addSubview:textfield5];
    UIButton *modify = [UIButton buttonWithType:UIButtonTypeCustom];
    [modify setSelector:@selector(modify) withTarget:self];
    modify.frame = CGRectMake(0, 0, 20, 20);
    [modify setImage:[UIImage imageNamed:@"Images/iconModify"]];
    textfield5.rightView = modify;
    textfield5.rightViewMode = UITextFieldViewModeAlways;
    self.modifyTextField = textfield5;
    
    UIView *line5 = [PxGlobal duplicate:line2];
    line5.top = textfield.bottom;
    [self.contentView addSubview:line5];
    
//    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(15, textfield5.bottom + 20, width-15*2, [PxGlobal getCustomerHeight:40])];
//    btn.layer.cornerRadius = 3;
//    btn.layer.masksToBounds = YES;
//    btn.backgroundColor = [UIColor colorWithHTMLStr:@"ff4e08"];
//    [btn setTitle:@"确定"];
//    btn.titleLabel.font = [UIFont systemFontOfSize:18];
//    btn.titleLabel.textColor = [UIColor colorWithHTMLStr:@"ffffff"];
//    [self.contentView addSubview:btn];
//    [btn setSelector:@selector(save) withTarget:self];
    
    [self setRightBtn:@"选择"];
}

-(void)modify
{
    if (!self.lastData)
        return;
    LLDLog(@"%@", self.lastData);
    [self.telTextField becomeFirstResponder];
    [PxGlobal deleteTabel:TABLE_SCHOOL withID:[self.lastData[@"id"] intValue]];
    [self.modifyTextField setText:@""];
    [self.telTextField setText:self.lastData[@"phone"]];
    [self.freightTextField setText:self.lastData[@"payFreight"]];
    [self.paymentTextField setText:self.lastData[@"payment"]];
    [self.pickerView setValue:self.lastData[@"areaNum"]];
    companyCode = self.lastData[@"expressCompany"];
    for (NSDictionary *dic in compArray) {
        if ([dic[@"value"] isEqualToString:companyCode]) {
            expressCompany = dic[@"label"];
            break;
        }
    }
    if (companyCode.length > 0) {
        [self setRightBtn:expressCompany];
    }
    [self setLogoTitleView];
}

-(void)setRightBtn:(NSString *)title
{
    UIButton *navBarRightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 44)];
    [navBarRightButton addTarget:self action:@selector(navBarRightBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [navBarRightButton setContentMode:UIViewContentModeCenter];
    
    [navBarRightButton setTitle:title];
    
    navBarRightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    UIColor *color1 = [UIColor colorWithHTMLStr:@"ff4e08"];
    [navBarRightButton setTitleColor:color1 forState:UIControlStateNormal];
    
    UIBarButtonItem *rightButtonItem=[[UIBarButtonItem alloc] initWithCustomView:navBarRightButton];
    
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       target:nil action:nil];
    if([LLYTSmallUtil iOSBigVersion] >= 6.5)
        negativeSpacer.width = -9;// it was -6 in iOS 6
    else
        negativeSpacer.width = 1;
    
    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:negativeSpacer,rightButtonItem/*this will be the button which u actually need*/, nil] animated:NO];
}

- (void)navBarRightBtnAction
{
    NSMutableArray *arr = [NSMutableArray new];
    int i = 0;
    int index = 0;
    for (NSDictionary *data in compArray) {
        if ([data[@"value"] isEqualToString:companyCode]) {
            index = i;
        }
        [arr addObject:data[@"label"]];
        i++;
    }
    if (!_pickViewController) {
        _pickViewController = [[PxAlertPickViewController alloc] initWithDataSource:arr];
        _pickViewController.delegate = self;
        _pickViewController.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        _pickViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        _pickViewController.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
    }
    [_pickViewController setData:index];
    [self presentViewController:_pickViewController animated:YES completion:nil];
}

- (void)buttonClick:(NSInteger)row
{
    NSDictionary *data = compArray[row];
    companyCode = data[@"value"];
    expressCompany = data[@"label"];
    [self setRightBtn:expressCompany];
    [self setLogoTitleView];
    // 保存选中的值，方便下次设置默认值
    [PxGlobal saveData:companyCode andKey:COMPANY_CODE];
    [PxGlobal saveData:expressCompany andKey:COMPANY_NAME];
}

- (UIView*)setLogoTitleView
{
    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 160, 44)];
    titleView.backgroundColor = [UIColor clearColor];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 160, 30)];
    titleLabel.font = [UIFont systemFontOfSize:18.f];
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = expressCompany;
    [titleView addSubview:titleLabel];
    
    UILabel *subTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 25, 160, 14)];
    subTitle.font = [UIFont systemFontOfSize:12.f];
    subTitle.textColor = [UIColor blackColor];
    subTitle.backgroundColor = [UIColor clearColor];
    subTitle.textAlignment = NSTextAlignmentCenter;
    subTitle.text = self.incomingParam[@"waybillNo"];
    [titleView addSubview:subTitle];
    
    self.navigationItem.titleView = titleView;
    
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gotoScanPage)];
    
    [titleView addGestureRecognizer:singleTap];
    
    return titleView;
}

-(BOOL)checkData
{
//    if ([super isEmpty:self.view.subviews])
//        return NO;
    NSString *phone = self.telTextField.text;
    if (companyCode.length <= 0) {
        [self showMSG:@"快递公司不能为空" withType:1];
        return NO;
    }
//    NSString *freight = self.freightTextField.text;
    BOOL isOk = [[PxFormValidate sharedInstance] checkPhone:phone];
    if (!isOk) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"手机号不符合现有规则，是否继续"] preferredStyle: UIAlertControllerStyleAlert];
        UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action){
            isContinues = YES;
            [self save];
        }];
        UIAlertAction *CancelAction = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDestructive handler:nil];
        [alertController addAction:OKAction];
        [alertController addAction:CancelAction];
        [self presentViewController:alertController animated:YES completion:nil];
        return NO;
    }
    return YES;
}

-(void)save
{
    if (!isContinues) {
        BOOL isOk = [self checkData];
        if (!isOk)
            return;
    }
    NSDate *senddate=[NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"MM-dd hh:mm"];
    NSString *locationString=[dateformatter stringFromDate:senddate];
    
    int rowId = [PxGlobal insertOrUpdateTable:TABLE_SCHOOL withData:@{
                                                        @"waybillNo":[PxGlobal getDicValue:@"waybillNo" fromDic:self.incomingParam],
                                                        @"expressCompany":companyCode,
                                                        @"areaCode":[_pickerView getSelectedValue],
                                                        @"phone":self.telTextField.text,
                                                        @"payFreight":self.freightTextField.text,
                                                        @"payment":self.paymentTextField.text,
                                                        @"sendTime":locationString
                                                          }];
    if (rowId != -1) {
        isContinues = NO;
        [self.modifyTextField setText:[self.telTextField.text formattedPhoneNo]];
        self.telTextField.text = @"";
        self.freightTextField.text = @"";
        self.paymentTextField.text = @"";
        [_pickerView plusLastColumnValue];
        self.lastData = [PxGlobal selectTable:TABLE_SCHOOL withRowId:[NSString stringWithFormat:@"%i", rowId]];
    }else {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"添加失败，请重新操作"] preferredStyle: UIAlertControllerStyleAlert];
        UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:nil];
        [alertController addAction:OKAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

-(void)gotoScanPage
{
    [self pushViewController:@"PxAVCaptureViewController" withIncomingParam:@{@"type":@"0",
                                                                              @"companyCode":companyCode,
                                                                              @"expressCompany":expressCompany
                                                                              }];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if (self.incomingParam) {
        companyCode = self.incomingParam[@"companyCode"];
        expressCompany = self.incomingParam[@"expressCompany"];
        if (companyCode.length > 0) {
            [self setRightBtn:expressCompany];
        }
        [self setLogoTitleView];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark textfield delegate


- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    LLDLog(@"textFieldShouldClear");
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField.tag == 10001)
        return NO;
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField.tag == 10000) {
        if (textField.text.length >= 10 && string.length > 0) {
            if (textField.text.length == 10)
                [textField setText:[NSString stringWithFormat:@"%@%@", textField.text, string]];
            [self save];
            return NO;
        }
    }
    
    return YES;
}

@end
